package com.ruoyi.web.controller.system;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.Rows;
import com.deepoove.poi.data.Tables;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.PoitlIOUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.InspectdatacsmqMapper;
import com.ruoyi.system.mapper.TCalibresultDataMapper;
import com.ruoyi.system.mapper.TWaterlevelshizhiwuchacourseMapper;
import com.ruoyi.system.service.ITWaterleveltasksService;
import com.ruoyi.system.service.ITraceabilityService;
import com.ruoyi.web.controller.unit.ServerTablePolicy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ICarspeedtaskService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 车速溯源Controller
 * 
 * @author ruoyi
 * @date 2024-11-29
 */
@RestController
@RequestMapping("/system/carspeedtask")
public class CarspeedtaskController extends BaseController
{
    @Autowired
    private ITraceabilityService traceabilityService;

    @Autowired
    private ICarspeedtaskService carspeedtaskService;

    /**
     * 查询车速溯源列表
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:list')")
    @GetMapping("/list")
    public TableDataInfo list(Carspeedtask carspeedtask)
    {
        startPage();
        List<Carspeedtask> list = carspeedtaskService.selectCarspeedtaskList(carspeedtask);
        return getDataTable(list);
    }

    /**
     * 导出车速溯源列表
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:export')")
    @Log(title = "车速溯源", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Carspeedtask carspeedtask)
    {
        List<Carspeedtask> list = carspeedtaskService.selectCarspeedtaskList(carspeedtask);
        ExcelUtil<Carspeedtask> util = new ExcelUtil<Carspeedtask>(Carspeedtask.class);
        util.exportExcel(response, list, "车速溯源数据");
    }

    /**
     * 获取车速溯源详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:query')")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") String ID)
    {
        return success(carspeedtaskService.selectCarspeedtaskByID(ID));
    }

    /**
     * 新增车速溯源
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:add')")
    @Log(title = "车速溯源", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Carspeedtask carspeedtask)
    {
        return toAjax(carspeedtaskService.insertCarspeedtask(carspeedtask));
    }

    /**
     * 修改车速溯源
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:edit')")
    @Log(title = "车速溯源", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Carspeedtask carspeedtask)
    {
        return toAjax(carspeedtaskService.updateCarspeedtask(carspeedtask));
    }

    /**
     * 删除车速溯源
     */
    @PreAuthorize("@ss.hasPermi('system:carspeedtask:remove')")
    @Log(title = "车速溯源", businessType = BusinessType.DELETE)
	@DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable String[] IDs)
    {
        return toAjax(carspeedtaskService.deleteCarspeedtaskByIDs(IDs));
    }


    @PostMapping(value = "/down/{taskId}")
    public void generateAndDownload(@PathVariable String taskId,HttpServletResponse response) throws Exception {

        // 获取模板文件流
        InputStream resourceAsStream =
                this.getClass().getResourceAsStream("D:\\hbsw\\cssy.docx");
        //poi-tl 配置
        ConfigureBuilder builder = Configure.builder();
        builder.useSpringEL(false);

        Map<String,Object> map = new HashMap<>();
//获取当前年
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
        String year = simpleDateFormat.format(new Date());
        map.put("year",year);
        // 伪造一个表格数据
        //单个表格
        ServerTableData oneTable = getServerTableData(taskId);
        map.put("oneTable",oneTable);

        builder.bind("oneTable",new ServerTablePolicy());

        XWPFTemplate template = XWPFTemplate.compile("D:\\hbsw\\cssy.docx", builder.build()).render(map);

        // 设置HTTP响应头，使浏览器知道这是一个Word文档
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=generatedDocument.docx");
        // 输出到HTTP响应流
        template.write(response.getOutputStream());
        template.close();
    }


    private ServerTableData getServerTableData(String taskId) {
        ServerTableData serverTableData = new ServerTableData();
        List<RowRenderData> serverDataList = new ArrayList<>();

       List<Traceability> traceabilityList = traceabilityService.selectTraceabilityListGroup(taskId);

        for(Traceability traceability : traceabilityList){

            RowRenderData serverData;
            serverData = Rows.of(traceability.getTestSpeed().toString(),
                    traceability.getTestInterval().toString(),
                    traceability.getOrientation(),
                    traceability.getFrequency().toString(),
                    traceability.getAbsTime().toString(),
                    traceability.getAbsSpeed().toString(),
                    traceability.getAbsInstantaneous().toString(),
                    traceability.getAbsChange()+"%").center().create();
            serverDataList.add(serverData);
        }


        List<Map<String, Object>> groupDataList = new ArrayList<>();
        //traceabilityList 根据实测速度去重
        List<Traceability>  testSpeetList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getTestSpeed))), ArrayList::new));
        for(Traceability traceability : testSpeetList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("typeName", traceability.getTestSpeed().toString());
            groupData.put("listSize", "36");
            groupDataList.add(groupData);
        }
//traceabilityList 自校距离段去重
        List<Traceability>  testIntervalList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getTestInterval))), ArrayList::new));
        for(Traceability traceability : testIntervalList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("testIntervalName", traceability.getTestInterval().toString());
            groupData.put("testIntervalSize", "36");
            groupDataList.add(groupData);
        }
        //traceabilityList 方向去重
        List<Traceability>  orientationList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getOrientation))), ArrayList::new));
        for(Traceability traceability : orientationList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("orientationName", traceability.getOrientation());
            groupData.put("orientationSize", "18");
            groupDataList.add(groupData);
        }
        //traceabilityList 测次去重
        List<Traceability>  frequencyList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getFrequency))), ArrayList::new));
        for(Traceability traceability : frequencyList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("frequencyName", traceability.getFrequency().toString());
            groupData.put("frequencySize", "6");
            groupDataList.add(groupData);
        }
        //traceabilityList 自校时间去重
        List<Traceability>  absTimeList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getAbsTime))), ArrayList::new));
        for(Traceability traceability : absTimeList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("absTimeName", traceability.getAbsTime().toString());
            groupData.put("absTimeSize", "6");
            groupDataList.add(groupData);
        }
        //traceabilityList 实测速度去重
        List<Traceability>  absSpeedList = traceabilityList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Traceability::getAbsSpeed))), ArrayList::new));
        for(Traceability traceability : absSpeedList){
            Map<String, Object> groupData = new HashMap<>();
            groupData.put("absSpeedName", traceability.getAbsSpeed().toString());
            groupData.put("absSpeedSize", "6");
            groupDataList.add(groupData);
        }
        serverTableData.setServerDataList(serverDataList);
        serverTableData.setGroupDataList(groupDataList);
        serverTableData.setMergeColumn(0);
        return serverTableData;
    }

}
